# -*- coding: utf-8 -*-
"""显示新闻详情"""
from flask import abort
from flask import g
from flask import jsonify
from flask import current_app
from flask import render_template
from flask import request

from info import db
from info.constants import CLICK_RANK_MAX_NEWS
from info.models import News, Comment, CommentLike, User
from info.utills.captcha.response_code import RET
from info.utills.common import check_user_login
from . import detail_blue

"""新闻详情"""


@detail_blue.route('/followed_user', methods=["POST"])
@check_user_login
def followed_user():
    """关注或者取消关注用户"""

    # 0. 取到自己的登录信息
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="未登录")

    # 1. 取参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2. 判断参数
    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 取到要被关注的用户
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    # 4. 根据要执行的操作去修改对应的数据
    if action == "follow":
        if other not in user.followed:
            # 当前用户的关注列表添加一个值
            user.followed.append(other)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前用户已被关注")
    else:
        # 取消关注
        if other in user.followed:
            user.followed.remove(other)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前用户未被关注")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@detail_blue.route('/comment_like', methods=['post'])
@check_user_login
def comment_like():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 获取数据 news_id，comment，parent_id
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')
    # 检验参数
    if not all([comment_id, action]):
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    if action not in ('add', 'remove'):
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    # 参数校验完毕，下面是点赞逻辑
    # 获取到要点赞的评论
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="没有该评论")
    # 判断该用户有没有点赞该评论
    comment_like_model = CommentLike.query.filter(CommentLike.user_id == user.id,
                                                  CommentLike.comment_id == comment.id).first()
    if action == 'add':
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment.id
            db.session.add(comment_like_model)
            comment.like_count += 1
    else:
        # 取消点赞
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1
    return jsonify(errno=RET.OK, errmsg="OK")


@detail_blue.route('/news_comment', methods=['post'])
@check_user_login
def newscomment():
    """评论"""
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 获取数据 news_id，comment，parent_id
    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')
    # 检验参数
    if not all([comment_content, news_id]):
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    # 判断该新闻新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有该新闻")
    # 3. 初始化一个评论模型，并且赋值
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id
    try:
        # return 的时候要用到comment的一些属性
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="评论添加失败")
    return jsonify(errno=RET.OK, errmsg="OK", data=comment.to_dict())


@detail_blue.route('/news_collect', methods=['post'])
@check_user_login
def news_collect():
    """收藏"""
    # 判断用户是否登陆
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 获取数据 news_id，action
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    # 检验参数
    if not all([action, news_id]):
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.DATAERR, errmsg="参数错误")
    # 判断该新闻新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有该新闻")
    # 收藏取消收藏逻辑
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    return jsonify(errno=RET.OK, errmsg="操作成功")


@detail_blue.route('/<int:news_id>')
@check_user_login
def news_detail(news_id):
    """显示新闻详情"""
    # 查看这条新闻id所对的新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not news:
        abort(404)
    # 点击数加1
    news.clicks += 1
    # 取到当前登陆的用户
    user = g.user
    # 点击排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict = []
    for new in news_list:
        news_dict.append(new.to_basic_dict())
    # 显示收藏或取消收藏
    is_collect = False
    is_followed = False
    if user:
        if news in user.collection_news:
            is_collect = True
        if news.user.followers.filter(User.id == user.id).count() > 0:
            is_followed = True
    # 查询当前新闻的所有评论数据
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
    # 查询当前登陆用户在当前新闻下的所有评论
    comment_ids = []
    if user:
        # 获取到当前新闻下的所有评论id
        commentIdlist = [commentIds.id for commentIds in comments]
        # 获取到当前新闻下的所有评论id，遍历这些id，在评论点赞表中查询，是当前用户的点赞记录
        # comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
        #                                          CommentLike.user_id == g.user.id).all()
        comment_like_list = CommentLike.query.filter(CommentLike.comment_id.in_(commentIdlist),
                                                     CommentLike.user_id == g.user.id).all()
        #  获取到对应的评论id
        comment_ids = [i.comment_id for i in comment_like_list]
    comments_dict_li = []
    for comment in comments:
        comments_dict = comment.to_dict()
        # 默认没有点赞
        comments_dict['is_like'] = False
        if comment.id in comment_ids:
            comments_dict['is_like'] = True
        comments_dict_li.append(comments_dict)

    # 准备数据
    data = {
        "news": news.to_dict(),
        "news_dict": news_dict,
        "user": user.to_dict() if user else None,
        "is_collected": is_collect,
        "comments": comments_dict_li,
        "is_followed": is_followed
    }
    # 模板渲染
    return render_template('news/detail.html', data=data)

    #  ajax请求是在满足一定条件触发，是局部刷新，如果网页刷新，就没了，
    # 除非在ajax请求时，将数据传给视图函数，操作数据库，视图函数每次再被请求时都会查询数据库，再将数据渲染到模板中
    # 模板渲染是全局刷新，当页面刷新后数据不会改变
